<template>
  <div class="wrap">
    <header-top title="登录" />
    <div class="content">
      <div class="area-logo">
        <img class="logo" :src="zbdLogo">
        <span class="login-sxy">尚小易</span>
        <span class="login-text" :class="{ mt30: !showSxy }">{{
          loginTitle
        }}</span>
      </div>
      <div class="input-group">
        <div class="input-row border">
          <van-field
            v-model="username"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
        </div>
        <div class="input-row border">
            <van-field
                v-model="password"
                :type="passwordType"
                name="密码"
                label="密码"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]">
              <template slot="right-icon">
                        <span class="solts" @click="switchPasswordType">
                            <van-icon name="eye" v-if="passwordType==='password'"/>
                            <van-icon name="closed-eye" v-else />
                        </span>
              </template>
            </van-field>
        </div>
        <div class="input-row border">
          <van-field
            v-model="captcha"
            name="验证码"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请输入验证码' }]"
          />
          <img
            ref="capchaImg"
            :src="captchaImgUrl"
            class="captcha-img"
            @click="getCaptchaImg"
          >
        </div>
      </div>
      <div class="btn-row">
        <van-button class="btn" round type="info" @click="bindLogin">登录</van-button>
      </div>
    </div>
  </div>
</template>
<script>
import { Toast, Dialog } from 'vant';
import HeaderTop from '../components/HeaderTop'
import { getCaptcha, zzdLogin } from "../api";
import zbdLogoJg from '../assets/tabbar/zbd-logo.png'
import { getDingDingCode } from '../utils/dd'
export default {
  data() {
    return {
      zbdLogo: zbdLogoJg,
      username: '',
      password: '',
      captcha: '', // 验证码
      positionTop: 0,
      captchaImgUrl: '', // 验证码图片地址
      loginTitle: '招标项目前置审批系统',
      showSxy: true,
      scookie: '',
      passwordType: 'password',
      sysName: ''
    }
  },
  mounted() {
     this.getCaptchaImg()
  },
  methods: {
    getCaptchaImg() {
      getCaptcha(1).then(res => {
        this.captchaImgUrl = 'data:image/jpeg;base64,' + res.data.base64
        this.scookie = res.data.scookie
      })
      
    },
    switchPasswordType() {
      this.passwordType = this.passwordType === 'password' ? 'text' : 'password'
    },
    async bindLogin() {
      if (!this.username) {
          Toast('请输入用户名');
					return;
				}
				if (!this.password) {
          Toast('请输入密码');
					return;
				}
        // const res = {code: "Od9a29e8c3984f00bb7039529c14de000cd99601" } || await getDingDingCode()
        const res = await getDingDingCode()

        console.log('1111:', res.code)
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
        });
				const params = {
					authCode: res.code,
					username: this.username,
					password: this.password,
					captcha: this.captcha,
					scookie: this.scookie,
					systemId: 1
				};
        zzdLogin(params).then(result => {
          console.log('result:', result)
          if (result.data.code === 1 && result.data.isSuccess) {
            Toast.loading({
              message: '登录成功',
              forbidClick: true,
            });
            console.log('zzdLogin:', result)
            this.toMain(result.data.user);
          } else if(result.data.code === 500){
            const loginErrorMsg = {
              'login_fail_timeout_captcha': '验证码错误请重试',
              'tiny_fail_wxCode': '服务器错误',
              'sso_login_fail': '用户名或密码错误',
              'sso_login_fail_zzd': '用户名或密码错误',
              'login_fail_check_captcha': '验证码错误请重试',
            }
            this.showErrAndRefresh(loginErrorMsg[result.data.msg] || '登录信息异常,请重新核对')
            // this.showErrAndRefresh(result.data.msg)
            this.reset()
          } else {
            this.captcha = ''
          }
        })
    },
    ArrayBufferToBase64(buffer) {
      //第一步，将ArrayBuffer转为二进制字符串
      var binary = '';
      var bytes = new Uint8Array(buffer);
      for (var len = bytes.byteLength, i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      //将二进制字符串转为base64字符串
      return window.btoa(binary);
    },
    toMain(userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        localStorage.setItem('zzdToken', userInfo.zzdToken)
        console.log('zzdToken:', userInfo.zzdToken)
				this.$router.replace({
					path: '/'
				});
		},
    showErrAndRefresh(errMsg) {
      Dialog.alert({
        message: errMsg,
      }).then(() => {
        // on close
        this.getCaptchaImg()
      });
		},
    reset() {
				this.username = ''
				this.password = ''
				this.captcha = ''
		},
  },
  components: {
    HeaderTop
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../common/stylus/mixin.styl';
</style>
<style lang="scss" scoped>
.content {
    display: flex;
    flex: 1;
    flex-direction: column;
    background-color: #fff;
  .area-logo {
    height: 25%;
    padding-top: 40px;
    margin-bottom: 10px;

    .logo {
      height: 75px;
      width: 75px;
      display: block;
      margin: 0 auto;
    }

    .login-sxy {
      margin: 15px 0;
      display: block;
      text-align: center;
      font-size: 24px;
      font-weight: 800;
      font-weight: 800;
      color: #2b518b;
      line-height: 24px;
      padding: 0 20px;
    }

    .login-text {
      display: block;
      text-align: center;
      font-size: 18px;
      font-weight: 800;
      font-weight: 800;
      color: rgba(43, 81, 139, 1);
      // line-height: 28px;
      padding: 0 20px;
    }
  }

  .action-row {
    display: flex;
    flex-direction: row;
    justify-content: center;
  }

  .input-group {
    margin-top: 40px;
    padding: 0 15px;

    &:before, &:after {
      height: 0;
      background-color: rgba(0, 0, 0, 0);
    }

    .input-row {
      display: flex;
      // width: 90vw;
      height: 40px;
      padding: 5px 0;
      margin: 5px 0;
      align-items: center;
      border-bottom: 2px solid #eee;
      font-size: 16px;
      .item-input {
        height: 40px;
        line-height: 40px;
      }

      .captcha-input {
        flex: 1 1 auto;
      }

      .captcha-img {
        flex: 1;
        height: 30px;
        will-change: transform;
      }
    }
  }

  .btn-row {
    margin-top: 60px;
    padding: 0 50px;
    .btn {
      width: 100%;
    }
  }

  .login-btn {
    background: #016DB2;
    border-radius: 4px;
  }
}

.mt30 {
  margin-top: 33px;
}

.action-row navigator {
  color: #007aff;
  padding: 0 20px;
}
</style>
